package com.lagou.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.regex.Pattern;

/**
 * @ClassName GetIP
 * @Description
 * @Author playboy
 * @Date 2021/6/8 2:21 下午
 * @Version 1.0
 **/
public class GetIP {

	public static void main(String[] args) {
		System.out.println(getLocalAddress().getHostAddress());
	}

	public static InetAddress getLocalAddress() {
		InetAddress localAddress = null;
		//第一次直接尝试通过InetAddress获取，判断获取到的是否满足isValidAddress中的三条规则
		try {
			localAddress = InetAddress.getLocalHost();
			if (isValidAddress(localAddress)) {
				return localAddress;
			}
		} catch (Throwable e) {
			System.out.println("Failed to retriving ip address, " + e.getMessage());
		}
		//如果不满足的化，获取所有的网卡，然后遍历每一张网卡
		try {
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			if (interfaces != null) {
				while (interfaces.hasMoreElements()) {
					try {
						NetworkInterface network = interfaces.nextElement();
						Enumeration<InetAddress> addresses = network.getInetAddresses();
						if (addresses != null) {
							while (addresses.hasMoreElements()) {
								try {
									InetAddress address = addresses.nextElement();
									if (isValidAddress(address)) {
										return address;
									}
								} catch (Throwable e) {
									System.out.println("Failed to retriving ip address, " + e.getMessage());
								}
							}
						}
					} catch (Throwable e) {
						System.out.println("Failed to retriving ip address, " + e.getMessage());
					}
				}
			}
		} catch (Throwable e) {
			System.out.println("Failed to retriving ip address, " + e.getMessage());
		}
		System.out.println("Could not get local host ip address, will use 127.0.0.1 instead.");
		return localAddress;
	}


	private static boolean isValidAddress(InetAddress address) {
		if (address == null || address.isLoopbackAddress()) {
			return false;
		}
		String name = address.getHostAddress();
		return (name != null
				&& !ANYHOST.equals(name)
				&& !LOCALHOST.equals(name)
				&& IP_PATTERN.matcher(name).matches());
	}

	public static final String LOCALHOST = "127.0.0.1";

	public static final String ANYHOST = "0.0.0.0";

	private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");

}
